package com.second.controler;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;

import com.second.dao.NewsDao;
import com.second.db.DbSqlSessionFactory;
import com.second.entity.News;

/**
 * Servlet implementation class NewsServlet
 */
@WebServlet("/news.do")
public class AddNewsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddNewsServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		//response.setContentType("text/html","utf-8");
		String ntitle=request.getParameter("title");
		String ntext=request.getParameter("content");
		String title=new String(ntitle.getBytes("iso-8859-1"),"utf-8");
		String text=new String(ntext.getBytes("iso-8859-1"),"utf-8");
	
		//String uid=(String) request.getSession().getAttribute("uid");
		Date date=new Date();
		News news=new News();
		news.setNtitle(title);
		news.setNtext(text);
		news.setNtime(date);
		//news.setUid(Integer.parseInt(uid));
		news.setUid(1);
		SqlSession ss=DbSqlSessionFactory.getSqlSession();
		NewsDao nd=ss.getMapper(NewsDao.class);
		int a=nd.addNews(news);
		ss.commit();
		ss.close();
		//System.out.println(a);
		if(a!=0){
			response.sendRedirect(request.getContextPath()+"/manage/manage-result.jsp");
		}else{
		request.getRequestDispatcher("manage/news-add.jsp").forward(request, response);}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request,response);
	}

}
